package cn.web.web_module.service.impl;

import cn.itcast.mapper.orderMapper;
import cn.itcast.pojo.horseman;
import cn.itcast.pojo.order;
import cn.itcast.pojo.orderItem;
import cn.itcast.pojo.user;
import cn.itcast.mapper.userMapper;
import cn.itcast.service.UserService;
import cn.itcast.service.orderService;
import cn.message.service.IHorsemanService;
import cn.web.web_module.service.AdminRelevantService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 张松
 * @Description:
 * @Date: Created in 9:57 2020/6/28
 * @Modified By:
 */
@Service("AdminRelevant")
public class AdminRelevantImpl implements AdminRelevantService {

    @Resource
    private UserService userService;

    @Resource
    private IHorsemanService horsemanService;

    @Resource
    private orderService orderService;

    @Resource
    private userMapper userMapper;

    @Resource
    private orderMapper orderMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;



    /**
     *
     * @Description: 查看昨天新增用户人数和下单详情
     *
     * @auther: 张松
     * @date: 10:58 2020/6/28
     * @param: []
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     *
     */
    public Map<String, Object> getYesterdayAdduserAndOrder(){
            List<user> yesterdayAdduser = userService.getYesterdayAdduser();
            List<order> yesterdayOrder = orderService.getYesterdayOrder();
            List<orderItem> yesterdayOrderWeightAndMoneyAndProductType = orderService.getYesterdayOrderWeightAndMoneyAndProductType();
            Map<String, Object> stringObjectMap = ifisEmptyAndAddMap(yesterdayAdduser, yesterdayOrder, yesterdayOrderWeightAndMoneyAndProductType);//判断这三个是否为空并且处理逻辑
            return stringObjectMap;
    }

    /**
     *
     * @Description: 查看全部日期的新增用户人数和下单详情数据
     *
     * @auther: 张松
     * @date: 14:28 2020/7/18
     * @param: []
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     *
     */
    public Map<String,Object> getEveryDayAddUserAndOrder(){
        Long localDateUtil = getLocalDateUtil(); // 得到最早数据和现在差了几天
        Map<String,Object> EveryDateMap= new LinkedHashMap<>();
        String everyDateMap = stringRedisTemplate.opsForValue().get("EveryDateMap");
        if (Strings.isNotBlank(everyDateMap)){
            return JSON.parseObject(everyDateMap,LinkedHashMap.class);
        }
        for (int i=0;i<localDateUtil;i++){
            List<user> everyDayAllAddUser = userService.getEveryDayAllAddUser(i);
            List<order> everyDayOrder = orderService.getEveryDayOrder(i);
            List<orderItem> everydayOrderWeightAndMoneyAndProductType = orderService.getEverydayOrderWeightAndMoneyAndProductType(i);
            if (everyDayAllAddUser.isEmpty()||everyDayAllAddUser.size()==0){

            }else if (everyDayOrder.isEmpty()||everyDayOrder.size()==0){

            }else if (everydayOrderWeightAndMoneyAndProductType.isEmpty()||everydayOrderWeightAndMoneyAndProductType.size()==0){

            }else {
                Map<String, Object> everyDayMap = ifisEmptyAndAddMap(everyDayAllAddUser, everyDayOrder, everydayOrderWeightAndMoneyAndProductType);
                EveryDateMap.put(LocalDate.now().minusDays(i+1).toString(),everyDayMap);
            }
        }
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String StringEveryDateMap = gson.toJson(EveryDateMap);
        stringRedisTemplate.opsForValue().set("EveryDateMap",StringEveryDateMap,60*60*24-NowDate(), TimeUnit.SECONDS);
        return EveryDateMap;
    }


    /**
     *
     * @Description: 获取现在几点钟,转成秒数
     *
     * @auther: 张松
     * @date: 10:38 2020/7/21
     * @param: []
     * @return: java.lang.Integer
     *
     */
    public Integer NowDate(){
        Date date = new Date();
        SimpleDateFormat sdfHH = new SimpleDateFormat("HH");
        String formatHH = sdfHH.format(date);
        SimpleDateFormat sdfmm = new SimpleDateFormat("mm");
        String formatmm = sdfmm.format(date);
        SimpleDateFormat sdfss = new SimpleDateFormat("ss");
        String formatss = sdfss.format(date);
        Integer nowDate = Integer.parseInt(formatHH)*60*60+Integer.parseInt(formatmm)*60+Integer.parseInt(formatss);
        return (nowDate);
    }


    /**
     *
     * @Description: 根据最早的一条数据判断时间,和现在的时间做比较,得出相差多少天
     *
     * @auther: 张松
     * @date: 13:56 2020/7/18
     * @param: []
     * @return: java.lang.Long
     *
     */
    public Long getLocalDateUtil(){
        user user = userMapper.selectMinDate();     //查找早进入的用户
        //时间转换开始
        Instant instant = user.getCreateTime().toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        LocalDate localDate = localDateTime.toLocalDate();
        //时间转换结束
        long days = localDate.until(LocalDate.now(), ChronoUnit.DAYS);
        return days;
    }




    /**
     *
     * @Description: 处理yesterdayAdduser,yesterdayOrder,yesterdayOrderWeightAndMoney 数据 返回需要的数
     *
     * @auther: 张松
     * @date: 10:36 2020/6/28
     * @param: [yesterdayAdduser  昨日新增用户数, yesterdayOrder 昨日订单详情, yesterdayOrderWeightAndMoney 昨日订单收益与收货重量]
     * @return: cn.itcast.util.ResponseEntity
     *
     */
    public Map<String,Object> ifisEmptyAndAddMap(List<user> yesterdayAdduser, List<order> yesterdayOrder, List<orderItem> yesterdayOrderWeightAndMoneyAndProductType){
        Map<String,Object> map = new HashMap<>();
        Integer allUserCount = userService.selectAllUserCount(); //全部的用户人数
        map.put("allUserCount",allUserCount);
        if (yesterdayAdduser.isEmpty()||yesterdayAdduser.size()==0){
            //map.put("新增用户人数",0);
        }else {
            List<user> horsemenAddUserlist = new ArrayList<>();
            Integer userAddcount=0; //其它新增用户数
            Integer AllAddUser=0;   //全部新增用户数
            for (user user : yesterdayAdduser) {
                if (user.getUserPhone()==null){
                    userAddcount+=user.getUserWxid();
                    AllAddUser+=user.getUserWxid();
                    map.put("otherAddUser",userAddcount);
                }else {
                    List<horseman> horsemen = horsemanService.selectHorsemanphone(user.getUserPhone());
                    if (!horsemen.isEmpty()||horsemen.size()!=0){
                        //horsemenAddUser.put(user.getUserName()+"电话号码:"+user.getUserPhone(),user.getUserWxid());
                        horsemenAddUserlist.add(user);
                        AllAddUser+=user.getUserWxid();
                    }else{
                        userAddcount+=user.getUserWxid();
                        AllAddUser+=user.getUserWxid();
                        map.put("otherAddUser",userAddcount);
                    }
                }

            }
            map.put("horsemenAddUser",horsemenAddUserlist);
            map.put("AllAddUser",AllAddUser);
        }
        if(yesterdayOrder.isEmpty()||yesterdayOrder.size()==0){
            //map.put("新增订单",0);
        }else {
            Integer countOrder=0;       //昨日订单量
            Integer completedOrder=0;   //已完成订单量
            Integer incompleteOrder=0;  //未完成订单量
            Integer excepOrder=0;       //异常订单量
            for (order order : yesterdayOrder) {
                countOrder+=order.getOrderCount();
                if (order.getOrderState().equals("已完成")){
                    completedOrder+=order.getOrderCount();
                }else if (order.getOrderState().equals("异常订单")){
                    excepOrder+=order.getOrderCount();
                }else{
                    incompleteOrder+=order.getOrderCount();
                }
            }
            map.put("countOrder",countOrder);
            map.put("completedOrder",completedOrder);
            map.put("incompleteOrder",incompleteOrder);
            map.put("excepOrder",excepOrder);
        }
        if (yesterdayOrderWeightAndMoneyAndProductType.isEmpty()||yesterdayOrderWeightAndMoneyAndProductType.size()==0){
            //map.put("昨天数据为空",0);
        }else {
            Double allWeight =0.0;//昨日收货总重量
            Double allMoney =0.0;//昨日全部收益
            for (orderItem orderItem : yesterdayOrderWeightAndMoneyAndProductType) {
                allWeight+=orderItem.getFinallyWeight();
                allMoney+=orderItem.getSum();
            }
            map.put("allWeight",allWeight);
            map.put("allMoney",allMoney);
            map.put("yesterdayOrderWeightAndMoneyAndProductType",yesterdayOrderWeightAndMoneyAndProductType);
        }

        return map;

    }


    /**
     *
     * @Description: 传入用户id 查看全部伙伴的订单
     *
     * @auther: 张松
     * @date: 17:48 2020/7/6
     * @param: [openId]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     *
     */
    @Override
    public PageInfo selectPartnerOrder(String openId,Integer pageNum,Integer pageSize) {
        List<String> allPartnerOrder = new ArrayList<>();
        List<user> oneDistribution = userMapper.findOneDistribution(openId);
        List<user> twoDistribution = userMapper.selectTwoDistribution(openId);
        setPartnerOpenId(allPartnerOrder,oneDistribution);
        setPartnerOpenId(allPartnerOrder,twoDistribution);
        PageHelper.startPage(pageNum,pageSize);
        List<order> orders = orderMapper.selectPartnerOrder(allPartnerOrder);
        PageInfo pageInfo = new PageInfo(orders);
        return pageInfo;
    }



    /**
     *
     * @Description: 设置需要查询的伙伴id
     *
     * @auther: 张松
     * @date: 17:54 2020/7/6
     * @param: [allPartnerOrder, user] allPartnerOrder 储存伙伴id的容器, user 推广的伙伴
     * @return: void
     *
     */
    void setPartnerOpenId(List<String> allPartnerOrder,List<user> user){
        user.forEach((v)->{
            allPartnerOrder.add(v.getOpenId());
        });
    }

/**
 *
 * @Description: 根据传输的条件查询
 *
 * @auther: 张松
 * @date: 15:31 2020/7/7
 * @param: [order]
 * @return: java.util.List<cn.itcast.pojo.order>
 *
 */
    @Override
    public PageInfo selectStateAndNumberAndUserName(order order,String openId,Integer pageNum,Integer pageSize) {
        List<String> allPartnerOrder = new ArrayList<>();
        List<user> oneDistribution = userMapper.findOneDistribution(openId);
        List<user> twoDistribution = userMapper.selectTwoDistribution(openId);
        setPartnerOpenId(allPartnerOrder,oneDistribution);
        setPartnerOpenId(allPartnerOrder,twoDistribution);
        PageHelper.startPage(pageNum,pageSize);
        List<order> orders = orderMapper.selectStateAndNumberAndUserName(order, allPartnerOrder);
        PageInfo pageInfo = new PageInfo(orders);
        return pageInfo;
    }


}
